package com.lancoo.answer.helper.answer;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Lifecycle;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lancoo.answer.R;
import com.lancoo.answer.model.AnswerConstant;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.bean.Child;
import com.lancoo.answer.model.bean.ExamViewBean;
import com.lancoo.answer.model.bean.Item;
import com.lancoo.answer.model.bean.Ques;
import com.lancoo.answer.model.bean.Type;
import com.lancoo.answer.model.entity.TaskControlBean;
import com.lancoo.answer.model.eventBean.AnswerSheetEventBean;
import com.lancoo.answer.model.eventBean.CompleteCurrentAnsPointEventBean;
import com.lancoo.answer.model.eventBean.FillAnswerEventBean;
import com.lancoo.answer.ui.paper.PaperFragment;
import com.lancoo.answer.util.DpUtils;
import com.lancoo.answer.util.SoftInputUtils;
import com.lancoo.answer.util.paperUtils.FragmentCommunicationUtils;
import com.rxjava.rxlife.RxLife;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by pengmi on 2021/6/7 15:46
 * Description:
 */
public class FillAnswerDialog extends DialogFragment{

    public static final String TAG = "FillAnswerDialog";
    private int currentItemIndex;
    private long subTime;
    private int lastItemIndex;
    private List<PopupAnswerBean> popupAnswerBeanList;
    private int defaultLoadIndex;
    private int typeIndex;
    private int quesIndex;
    private int childIndex;
    private ViewPager2 viewPager2;


    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null&& getContext()!=null&&dialog.getWindow()!=null) {
            Window window = dialog.getWindow();
            WindowManager.LayoutParams attributes = window.getAttributes();
            attributes.dimAmount=0.1f;
            attributes.gravity= Gravity.BOTTOM;
            attributes.width= DpUtils.getWidthInPx(getContext());
            dialog.getWindow().setAttributes(attributes);
        }
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(getDialog()==null|| getDialog().getWindow()==null){
            return null;
        }
        getDialog().getWindow().getAttributes().windowAnimations = R.style.answerFill_DialogAnimation;
        View convertView = inflater.inflate(R.layout.ev_dialog_layout_fill_answer, container, false);
        initView(convertView);
        return convertView;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.answerSheet_ColorStyle);
    }


    private void initView(View view){
        if(getArguments()==null){
            return;
        }
        subTime=System.currentTimeMillis();
        typeIndex = getArguments().getInt(AnswerConstant.KEY_TYPEINDEX);
        quesIndex = getArguments().getInt(AnswerConstant.KEY_QUESINDEX);
        childIndex = getArguments().getInt(AnswerConstant.KEY_CHILDINDEX);
        int itemIndex = getArguments().getInt(AnswerConstant.KEY_ITEMINDEX);
        ExamViewBean constantExamBean = ConstantBean.Companion.getConstantExamBean();
        if(constantExamBean==null){
            return;
        }
        List<Type> typeList = constantExamBean.getTypeList();
        if(typeList==null){
            return;
        }
        List<Ques> quesList = typeList.get(typeIndex).getQuesList();
        if(quesList==null){
            return;
        }

        popupAnswerBeanList = new ArrayList<>();
        defaultLoadIndex = 0;

        Observable.create((ObservableOnSubscribe<String>) emitter -> {
                    int currentQuesIndex=0;
                    for (Ques ques:quesList){
                        if(ques.getChildList()==null){
                            return ;
                        }
                        int answerChildIndex=0;
                        for (Child child:ques.getChildList()){
                            int answerItemIndex=0;
                            if(child.getItemList()==null){
                                continue;
                            }
                            for (Item item:child.getItemList()){
                                if(childIndex ==answerChildIndex&&itemIndex==answerItemIndex&&
                                        currentQuesIndex== quesIndex){
                                    defaultLoadIndex =popupAnswerBeanList.size();
                                }
                                PopupAnswerBean bean=new PopupAnswerBean();
                                bean.setItem(item);
                                bean.setTypeIndex(typeIndex);
                                bean.setQuesIndex(currentQuesIndex);
                                bean.setChildIndex(answerChildIndex);
                                bean.setItemIndex(answerItemIndex);
                                popupAnswerBeanList.add(bean);
                                answerItemIndex++;
                            }
                            answerChildIndex++;
                        }
                        currentQuesIndex++;
                    }
                    emitter.onNext("");
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.as(this))
                .subscribe(integer ->{
                    viewPager2 = view.findViewById(R.id.viewpager2);
                    viewPager2.setAdapter(new FragmentStateAdapter(this) {
                        @NonNull
                        @Override
                        public Fragment createFragment(int position) {
                            PopupAnswerBean popupAnswerBean = popupAnswerBeanList.get(position);
                            int typeIndex = popupAnswerBean.getTypeIndex();
                            int quesIndex = popupAnswerBean.getQuesIndex();
                            int childIndex = popupAnswerBean.getChildIndex();
                            int itemIndex = popupAnswerBean.getItemIndex();
                            return FillAnswerFragment.loadFragment(typeIndex,
                                    quesIndex,
                                    childIndex, itemIndex);
                        }
                        @Override
                        public int getItemCount() {
                            return popupAnswerBeanList.size();
                        }
                    });
                    viewPager2.setCurrentItem(defaultLoadIndex,false);
                    currentItemIndex=defaultLoadIndex;
                    lastItemIndex=currentItemIndex;
                    viewPager2.postDelayed(() -> {
                        if(getContext()==null){
                            return;
                        }
                        SoftInputUtils.showSoftInput(getContext());
                        if(getContext() == null || viewPager2.getAdapter() == null){
                            return;
                        }
                        long itemId = viewPager2.getAdapter().getItemId(viewPager2.getCurrentItem());
                        Fragment topicBaseFragment = getChildFragmentManager().findFragmentByTag("f"+itemId);
                        if(topicBaseFragment instanceof FillAnswerFragment){
                            ((FillAnswerFragment) topicBaseFragment).getEditTextFocus();
//                            SoftInputUtils.showSoftInput(topicBaseFragment.getContext());
                        }
                    },100);
                    viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
                        @Override
                        public void onPageSelected(int position) {
                            super.onPageSelected(position);
                            currentItemIndex=position;
                            if(getContext()==null){
                                return;
                            }
                            updateAnswerCallBack(1);
                            Single.timer(100, TimeUnit.MILLISECONDS)
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .as(RxLife.as(FillAnswerDialog.this, Lifecycle.Event.ON_PAUSE))
                                    .subscribe(aLong ->  {
                                        if(getContext() == null || viewPager2.getAdapter() == null){
                                            return;
                                        }
                                        long itemId = viewPager2.getAdapter().getItemId(viewPager2.getCurrentItem());
                                        Fragment topicBaseFragment = getChildFragmentManager().findFragmentByTag("f"+itemId);
                                        if(topicBaseFragment instanceof FillAnswerFragment){
                                            ((FillAnswerFragment) topicBaseFragment).getEditTextFocus();
                                        }
                                    });
                        }
                    });
                });

    }

    /**
     *
     * @param parenterFragment frgmentManger
     * @param typeIndex 题型下标
     * @param quesIndex 大题下标
     * @param childIntex 小题下标
     * @param itemIndex 答题点下标 FillAnswerDialog.launchFillAnswerDialog
     */
    public static void launchFillAnswerDialog(Fragment parenterFragment,
                                              int typeIndex, int quesIndex, int childIntex,
                                              int itemIndex){
        Log.e("202212121", "showTest dialog" );
        if(!(parenterFragment instanceof PaperFragment)){
            parenterFragment=parenterFragment.getParentFragment();
        }
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        if(parenterFragment==null){
            Log.d("shishi","im in1");

            return;
        }
        if(taskControlBean==null){
            Log.d("shishi","im in2");

            return;
        }
        if(taskControlBean.getEnableAnwer()==0){
            Log.d("shishi","im in3");

            return;
        }
        if(System.currentTimeMillis()-ConstantBean.Companion.getOnClickSubTime()<1000){
            Log.d("shishi","im in4");
            return;
        }
        ConstantBean.Companion.setOnClickSubTime(System.currentTimeMillis());
        FragmentCommunicationUtils.unableVpChange(parenterFragment);
        FillAnswerDialog fragment=new FillAnswerDialog();
        Bundle mBundle=new Bundle();
        mBundle.putInt(AnswerConstant.KEY_TYPEINDEX,typeIndex);
        mBundle.putInt(AnswerConstant.KEY_QUESINDEX,quesIndex);
        mBundle.putInt(AnswerConstant.KEY_CHILDINDEX,childIntex);
        mBundle.putInt(AnswerConstant.KEY_ITEMINDEX,itemIndex);
        Log.d("shishi","im in5");
        fragment.setArguments(mBundle);
        fragment.show(parenterFragment.getChildFragmentManager().beginTransaction(),TAG);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDismiss(@NonNull DialogInterface dialog) {
        Log.e(TAG, "dismissAllowingStateLoss: ");
        EventBus.getDefault().post(new CompleteCurrentAnsPointEventBean());
        super.onDismiss(dialog);
    }



    public void updateAnswerCallBack(int msgType){
        if(System.currentTimeMillis()-subTime<300){
            return;
        }
        ConstantBean.Companion.setOnClickSubTime(System.currentTimeMillis());
        PopupAnswerBean popupAnswerBean = popupAnswerBeanList.get(currentItemIndex);
        PopupAnswerBean lastPopupAnswerBean = popupAnswerBeanList.get(lastItemIndex);
        int typeIndex = popupAnswerBean.getTypeIndex();
        int quesIndex = popupAnswerBean.getQuesIndex();
        int childIndex = popupAnswerBean.getChildIndex();
        int itemIndex = popupAnswerBean.getItemIndex();
        AnswerSheetEventBean answerSheetEvent=new AnswerSheetEventBean();
        answerSheetEvent.setTypeIndex(typeIndex);
        answerSheetEvent.setQuesIndex(quesIndex);
        answerSheetEvent.setChildIndex(childIndex);
        answerSheetEvent.setItemIndex(itemIndex);
        answerSheetEvent.setEventType(1);
        EventBus.getDefault().post(answerSheetEvent);
        lastItemIndex=currentItemIndex;
    }

    public boolean forceUpdateAnswerIndex(int typeIndex, int quesIndex){
        if(typeIndex==this.typeIndex){
            if(quesIndex!=this.quesIndex){
                if(viewPager2!=null){
                    for (int i = 0; i < popupAnswerBeanList.size(); i++) {
                        PopupAnswerBean popupAnswerBean = popupAnswerBeanList.get(i);
                        if(popupAnswerBean.getTypeIndex()==typeIndex&&popupAnswerBean.getQuesIndex()==quesIndex){
                            viewPager2.setCurrentItem(i,true);
                            break;
                        }
                    }
                }
            }
            return true;
        }else{
            dismiss();
        }
        return false;
    }
}
